#!/bin/bash
CMAKE_PARAMS=""

WORKDIR=${WORKDIR/D:/\/d}
WORKDIR=${WORKDIR//\\/\/}
TEST_SUITE_DIR=${TEST_SUITE_DIR/D:/\/d}
TARGET=arm-liteos
DISABLED_TESTS="libomp_basic;FFmpeg;LZ4;CLAMR;LMbench"

echo "Currently in ${WORKDIR}"
mkdir ${TARGET}
cd ${TARGET}
echo "###### Compilation for ${TARGET} ######"
echo "Currently in ${WORKDIR}/${TARGET}"
echo "Using ${CLANG_TOOLCHAIN} and ${TEST_SUITE_DIR}"

if [[ ${TEST_SUITE_SUBDIRS} ]]; then
    echo "Compiling follow subdirs: '${TEST_SUITE_SUBDIRS}'"
    CMAKE_PARAMS+=" -DTEST_SUITE_SUBDIRS='${TEST_SUITE_SUBDIRS}'"
fi
if [[ ${DISABLED_TESTS} ]]; then
    echo "'${DISABLED_TESTS}' are disabled"
    CMAKE_PARAMS+=" -DDISABLED_TESTS='${DISABLED_TESTS}'"
fi

echo "Configuring with CMake"
CXX_LIBS=${WORKDIR}/${CLANG_TOOLCHAIN}/lib/${TARGET}/c++
TEST_SUITE_LINKER_FLAGS="-fuse-ld=${WORKDIR}/${CLANG_TOOLCHAIN}/bin/ld.lld -L${CXX_LIBS} -B${CXX_LIBS} -static"
(set -x; 
/usr/bin/cmake -DCMAKE_C_COMPILER=${WORKDIR}/${CLANG_TOOLCHAIN}/bin/clang.exe \
               -DCMAKE_CXX_COMPILER=${WORKDIR}/${CLANG_TOOLCHAIN}/bin/clang++.exe \
               ${TEST_SUITE_DIR} \
               -DCMAKE_SYSROOT:STRING=${WIN_MUSL_SYSROOT} \
               -DCMAKE_EXE_LINKER_FLAGS="${TEST_SUITE_LINKER_FLAGS}" \
               -DCMAKE_TOOLCHAIN_FILE:FILEPATH=${TEST_SUITE_DIR}/cmake/caches/LiteOSLLVM.cmake \
               -DTEST_SUITE_BUILD_TARGET=${TARGET} \
               -DCMAKE_C_FLAGS=-O3 -DTEST_SUITE_COLLECT_COMPILE_TIME=OFF \
               -DCMAKE_STRIP:STRING=${WORKDIR}/${CLANG_TOOLCHAIN}/bin/llvm-strip \
               -DCMAKE_SYSTEM_NAME=Generic \
               -DTEST_SUITE_ARM_FP_TYPE:STRING=hard \
               ${CMAKE_PARAMS}
) || cmake_code=$?
cp CMakeFiles/CMakeOutput.log ${WORKDIR}/res_cmake_output_${TARGET}.log
cp CMakeFiles/CMakeError.log ${WORKDIR}/res_cmake_error_${TARGET}.log

if [[ "${cmake_code}" -ne 0 ]]; then
    echo "Error: CMake configuring for ${TARGET} has failed! Please, check log in artifacts" >>  ${WORKDIR}/job_result.txt
else
    echo "Compiling... Invoking make"
    (set -x; /usr/bin/make -k -j 10 VERBOSE=1 all 1> >(tee -a ${WORKDIR}/res_make_output_${TARGET}.txt) 2> >(tee -a ${WORKDIR}/res_make_error_${TARGET}.txt >&2)) || make_code=$? 
    if [[ "${make_code}" -ne 0 ]]; then
        echo "Error: Compilation for ${TARGET} has failed! Please, check log in artifacts" >>  ${WORKDIR}/job_result.txt
    else 
        echo "!!! Compilation for ${TARGET} finished successfully !!! But better check job console log, just in case" >>  ${WORKDIR}/job_result.txt
    fi
fi
cd ${WORKDIR}
